/**
 * Copyright 2009-2015 the original author or authors.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.ibatis.reflection;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * 默认反射器工厂方法实现
 *
 * {@link ReflectorFactory}
 */
public class DefaultReflectorFactory implements ReflectorFactory {
    private boolean classCacheEnabled = true;
    /**
     * Reflector 的缓存映射
     * <p>
     * KEY：类
     * VALUE：Reflector 对象
     * <p>
     * A Map提供线程安全和原子性保证。
     * 内存一致性效果：与其他并发集合一样，在将对象放入ConcurrentMap作为键或happen-before之前的线程中的操作，在另一个线程中从ConcurrentMap访问或删除该对象之后。
     */
    private final ConcurrentMap<Class<?>, Reflector> reflectorMap = new ConcurrentHashMap<>();

    public DefaultReflectorFactory() {
    }

    @Override
    public boolean isClassCacheEnabled() {
        return classCacheEnabled;
    }

    @Override
    public void setClassCacheEnabled(boolean classCacheEnabled) {
        this.classCacheEnabled = classCacheEnabled;
    }

    @Override
    public Reflector findForClass(Class<?> type) {
        if (classCacheEnabled) {
            // 开启缓存，则从 reflectorMap 中获取
            // synchronized (type) removed see issue #461
            Reflector cached = reflectorMap.get(type);
            // 不存在，则进行创建
            //return reflectorMap.computeIfAbsent(type,Reflector::new);  jdk8简写下面逻辑
            if (cached == null) {
                cached = new Reflector(type);
                reflectorMap.put(type, cached);
            }
            return cached;
        } else {
            // 关闭缓存，则创建 Reflector 对象
            return new Reflector(type);
        }
    }

}
